# GF_PY312_CLASS_PyMongo_4_x.py
# Create by GF 2025-04-10 15:51

import json
import pymongo

# ##################################################

class PyMongo_4_x(object):

    def __init__(self):

        self.MONGO_HOST = '127.0.0.1'
        self.MONGO_USER = ''
        self.MONGO_PASSWORD = ''

    def Append_Records_from_JSON(self, Database:str, Collection:str, JSON_File:str):

        mongo = pymongo.MongoClient(self.MONGO_HOST, 27017)
        # ..........................................
        mongo_db = mongo[Database]
        mongo_collection = mongo_db[Collection]
        # ..........................................
        # 加载 JSON 数据
        Target_JSON_File = open(JSON_File, mode='r', encoding="utf-8")
        Target_JSON_Data = json.load(Target_JSON_File)  # 加载 JSON 数据到 Python 3 对象中 (通常是列表形式)
        Target_JSON_File.close()
        # ..........................................
        # PyMongo 4.x 中 pymongo.MongoClient(...)["database"]["collection"].insert_one():
        # - Explain:
        #   一次插入 1 个文档
        # - Returns:
        #   InsertOneResult('67f4e29402c1a8db45a82792', acknowledged=True)
        # ..........................................
        # PyMongo 4.x 中 pymongo.MongoClient(...)["database"]["collection"].insert_many():
        # - Explain:
        #   一次插入 N 个文档
        # - Returns:
        #   InsertManyResult(['67f4de6c02c1a8db45a8270e',
        #                     '67f4de8602c1a8db45a82710',
        #                     ......,
        #                     '67f4df5402c1a8db45a82730',], acknowledged=True)
        # ..........................................
        Counter = 0
        for doc in Target_JSON_Data:
            mongo_collection.insert_one(doc)
            # ......................................
            Counter = Counter + 1
        # ..........................................
        return Counter

    def Append_Records_from_JSON_with_Password(self, Database:str, Collection:str, JSON_File:str):

        mongo = pymongo.MongoClient( # 连接到 MongoDB 数据库
            "mongodb://%s:%s@%s:27017" % ( # Example: "mongodb://root:abcd1234@127.0.0.1:27017"
                self.MONGO_USER, self.MONGO_PASSWORD, self.MONGO_HOST
            )
        )
        # ..........................................
        mongo_db = mongo[Database]
        mongo_collection = mongo_db[Collection]
        # ..........................................
        # 加载 JSON 数据
        Target_JSON_File = open(JSON_File, mode='r', encoding="utf-8")
        Target_JSON_Data = json.load(Target_JSON_File)  # 加载 JSON 数据到 Python 3 对象中 (通常是列表形式)
        Target_JSON_File.close()
        # ..........................................
        Result = mongo_collection.insert_many(Target_JSON_Data)
        # ..........................................
        return Result

# EOF Signed by GF.
